from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
import numpy as np
import cv2
import sys
sys.path.append('./build')
import simple_camera

class Record(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setObjectName("Record")
        self.resize(1094, 508)
        self.gridLayout_2 = QtWidgets.QGridLayout(self)
        self.gridLayout_2.setContentsMargins(11, 11, 11, 11)
        self.gridLayout_2.setSpacing(6)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.record_button = QtWidgets.QPushButton(self)
        self.record_button.setMinimumSize(QtCore.QSize(131, 41))
        self.record_button.setObjectName("record_button")
        self.horizontalLayout.addWidget(self.record_button)
        self.focus_plus_button = QtWidgets.QPushButton(self)
        self.focus_plus_button.setMinimumSize(QtCore.QSize(27, 41))
        self.focus_plus_button.setMaximumSize(QtCore.QSize(27, 41))
        self.focus_plus_button.setObjectName("+")
        self.horizontalLayout.addWidget(self.focus_plus_button)
        self.focus_sub_button = QtWidgets.QPushButton(self)
        self.focus_sub_button.setMinimumSize(QtCore.QSize(27, 41))
        self.focus_sub_button.setMaximumSize(QtCore.QSize(27, 41))
        self.focus_sub_button.setObjectName("-")
        self.horizontalLayout.addWidget(self.focus_sub_button)
        self.pushButton_2 = QtWidgets.QPushButton(self)
        self.pushButton_2.setMinimumSize(QtCore.QSize(131, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.path_display = QtWidgets.QLineEdit(self)
        self.path_display.setMinimumSize(QtCore.QSize(600, 0))
        self.path_display.setMaximumSize(QtCore.QSize(1000, 16777215))
        self.path_display.setReadOnly(True)
        self.path_display.setObjectName("path_display")
        self.horizontalLayout.addWidget(self.path_display)
        self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.graphicsView = QtWidgets.QGraphicsView(self)
        self.graphicsView.setObjectName("graphicsView")
        self.gridLayout_2.addWidget(self.graphicsView, 1, 0, 1, 1)

        self.retranslateUi()

        self.scene = QtWidgets.QGraphicsScene()
        self.camera = simple_camera.SimpleCamera()
        self.camera.startCapture()

        # Timer for periodic updates
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.update_image)
        self.timer.start(10)  # Update every 30 ms

        # Variable to store recording state and save path
        self.is_recording = False
        self.save_path = None
        self.data_file = None  # File handle for .data file

    def retranslateUi(self):
        self.setWindowTitle("Record")
        self.record_button.setText("Start Recording")
        self.record_button.clicked.connect(self.start_recording)
        self.focus_plus_button.setText("+")
        self.focus_plus_button.pressed.connect(self.focus_plus)
        self.focus_plus_button.released.connect(self.focus_plus)
        self.focus_sub_button.setText("-")
        self.focus_sub_button.pressed.connect(self.focus_sub)
        self.focus_sub_button.released.connect(self.focus_sub)
        self.pushButton_2.setText("Choose Save Path")
        self.pushButton_2.clicked.connect(self.choose_save_path)

    def focus_plus(self):
        # 获取信号来源的具体类型
        sender = self.sender()
        if sender.isDown():
            self.camera.focus_setup(20)
        else:
            self.camera.focus_setup(0)

    def focus_sub(self):
        # 获取信号来源的具体类型
        sender = self.sender()
        if sender.isDown():
            self.camera.focus_setup(-20)
        else:
            self.camera.focus_setup(0)

    def start_recording(self):
        # Toggle recording state
        self.is_recording = not self.is_recording
        if self.is_recording:
            self.record_button.setText("Stop Recording")
            if self.save_path:
                # Open the .data file for writing binary data
                self.data_file = open(self.save_path, 'wb')
        else:
            self.record_button.setText("Start Recording")
            if self.data_file:
                # Close the .data file when stopping recording
                self.data_file.close()
                self.data_file = None
    def choose_save_path(self):
        # Open file dialog to choose save path
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_path, _ = QFileDialog.getSaveFileName(self, "Save Image Data", "", "Data Files (*.data);;All Files (*)",
                                                   options=options)
        if file_path:
            self.save_path = file_path + ".data"
            self.path_display.setText(self.save_path)

    def update_image(self):
        raw_data = self.camera.getImage()
        if raw_data:
            src = np.array(raw_data, dtype=np.uint16).reshape(288, 384)
            image = cv2.normalize(src, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
            h, w = image.shape
            q_image = QtGui.QImage(image.data, w, h, w, QtGui.QImage.Format_Grayscale8)
            item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap.fromImage(q_image))
            # 清空场景并添加新的 QPixmapItem
            self.scene.clear()
            self.scene.addItem(item)

            self.graphicsView.setScene(self.scene)
            self.graphicsView.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
            # Save the image binary data if recording is active
            if self.is_recording and self.data_file:
                self.data_file.write(src.tobytes())  # Write binary data to file
        else:
            print("raw_data is None")

    def closeEvent(self, event):
        self.camera.stopCapture()
        if self.data_file:
            self.data_file.close()  # Ensure the file is closed if the window is closed
        event.accept()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Widget = Record()
    Widget.show()
    sys.exit(app.exec_())
